<template>
  <div class="app-container">
    <!-- <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模板名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入模板名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="地域以及费用" prop="regionInfo">
        <el-input
          v-model="queryParams.regionInfo"
          placeholder="请输入地域以及费用"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="指定包邮开关" prop="appoint">
        <el-input
          v-model="queryParams.appoint"
          placeholder="请输入指定包邮开关"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="指定包邮内容" prop="appointInfo">
        <el-input
          v-model="queryParams.appointInfo"
          placeholder="请输入指定包邮内容"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="isDel">
        <el-input
          v-model="queryParams.isDel"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input
          v-model="queryParams.sort"
          placeholder="请输入排序"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form> -->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['templates:templates:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['templates:templates:edit']"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['templates:templates:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['templates:templates:export']">导出</el-button>
      </el-col> -->
      <right-toolbar
        :show-search.sync="showSearch"
        :search="false"
        :columns="columns"
        @queryTable="getList"
        @columns-change="onColumnChange"
      />
    </el-row>

    <el-table v-loading="loading" :data="templatesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        v-for="col in filteredColumns"
        :key="col.prop"
        :label="col.label"
        header-align="center"
        :align="col.align || 'center'"
        :prop="col.prop"
        :width="col.width"
      >
        <template slot-scope="{row,column,$index}">
          <!-- <div v-html="col.render(row, column, $index)"  v-if="col.render"></div> -->
          <CellRender
            v-if="col.render"
            :row="row"
            :column="column"
            :col-config="col"
            :index="$index"
            :render="col.render"
          />
          <template v-else>
            {{ row[col.prop] }}
          </template>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['templates:templates:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-hasPermi="['templates:templates:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改运费模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" inline>
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-row>
          <el-col :span="24">
            <el-form-item label="计费方式" prop="type">
              <el-radio-group v-model="form.type" class="radio">
                <el-radio :label="1">按件数</el-radio>
                <el-radio :label="2">按重量</el-radio>
                <el-radio :label="3">按体积</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="配送区域及运费" prop="regionInfo">
          <el-table :data="regionInfoList" border size="mini">
            <el-table-column prop="regionName" label="可配送区域" header-align="center" width="150" />
            <el-table-column prop="first" label="首件" header-align="center" width="120">
              <template slot="header">
                <span v-if="form.type == 1">首件</span>
                <span v-else-if="form.type == 2">首件重量(KG)</span>
                <span v-else>首件体积(m³)</span>
              </template>
              <template slot-scope="{row}">
                <el-input v-model="row.first" />
              </template>
            </el-table-column>
            <el-table-column prop="price" label="运费（元）" header-align="center" width="100">
              <template slot-scope="{row}">
                <el-input v-model="row.price" />
              </template>
            </el-table-column>
            <el-table-column prop="_continue" label="续件" header-align="center" width="120">
              <template slot="header">
                <span v-if="form.type == 1">续件</span>
                <span v-else-if="form.type == 2">续件重量(KG)</span>
                <span v-else>续件体积(m³)</span>
              </template>
              <template slot-scope="{row}">
                <el-input v-model="row._continue" />
              </template>
            </el-table-column>
            <el-table-column prop="continue_price" label="续费（元）" header-align="center" width="100">
              <template slot-scope="{row}">
                <el-input v-model="row.continue_price" />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="80">
              <template slot-scope="{row}">
                <el-button
                  v-if="row.regionName !== '默认全国'"
                  type="danger"
                  size="mini"
                  @click="delList($index, 'regionInfoList')"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" icon="md-add" @click="addList('regionInfoList')">单独添加配送区域</el-button>
        </el-form-item>
        <el-form-item label="指定包邮" prop="appoint">
          <el-radio-group v-model="form.appoint">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="0">关闭</el-radio>
          </el-radio-group>
          <template v-if="form.appoint === 1">
            <el-table :data="appointInfoList" empty-text="暂无数据" border size="mini">
              <el-table-column prop="placeName" label="选择地区" header-align="center" width="150" />
              <el-table-column prop="a_num" label="包邮件数" width="120" align="center">
                <template slot="header">
                  <span v-if="form.type == 1">包邮件数</span>
                  <span v-else-if="form.type == 2">包邮重量(KG)</span>
                  <span v-else>包邮体积(m³)</span>
                </template>
                <template slot-scope="scope">
                  <span>
                    <el-input v-model="scope.row.a_num" />
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="a_price" label="包邮金额（元）" width="120" align="center">
                <template slot-scope="scope">
                  <span>
                    <el-input v-model="scope.row.a_price" />
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="80">
                <template slot-scope="{$index}">
                  <el-button type="danger" size="mini" @click="delList($index, 'appointInfoList')">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button type="primary" icon="md-add" @click="addList('appointInfoList')">单独指定包邮</el-button>
          </template>
        </el-form-item>
        <el-row>
          <el-col :span="24">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" :min="0" placeholder="输入值越大越靠前" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <CitySelector :visible.sync="visible" @save="onCitiesSelected" />
  </div>
</template>

<script>
import { listTemplates, getTemplates, delTemplates, addTemplates, updateTemplates } from '@/api/templates/templates'
import tableColumnSelect from '@/mixin/tableColumnSelect'
import CitySelector from './CitySelector'

export default {
  name: 'Templates',
  components: {
    CitySelector
  },
  mixins: [tableColumnSelect],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 运费模板表格数据
      templatesList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        type: undefined,
        regionInfo: undefined,
        appoint: undefined,
        appointInfo: undefined,
        isDel: undefined,
        sort: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: '模板名称不能为空', trigger: 'blur' }
        ]
      },
      columns: [
        // {
        //   label:"模板ID" ,
        //   prop:"id"
        // },
        { label: '模板名称', prop: 'name' },
        { label: '计费方式', prop: 'type' },
        { label: '指定包邮开关', prop: 'appoint' },
        { label: '添加时间', prop: 'createTime' },
        { label: '排序', prop: 'sort' }
      ],
      regionInfoList: [],
      appointInfoList: [],
      visible: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询运费模板列表 */
    getList() {
      this.loading = true
      listTemplates(this.queryParams).then(response => {
        this.templatesList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        name: '',
        type: 1,
        regionInfo: undefined,
        appoint: 0,
        appointInfo: undefined,
        sort: 0
      }
      this.regionInfoList = [
        {
          region: [
            {
              name: '默认全国',
              cityId: 0
            }
          ],
          regionName: '默认全国',
          first: 1,
          price: 0,
          _continue: 1,
          continue_price: 0
        }
      ]
      this.appointInfoList = []
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加运费模板'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true
      this.reset()
      const id = row.id || this.ids
      getTemplates(id).then(({ data }) => {
        this.loading = false
        this.form = data
        this.regionInfoList = data.regionInfo
        this.appointInfoList = data.appointInfo
        this.open = true
        this.title = '修改运费模板'
      })
    },
    checkFormList() {
      let isValid = true
      const { appointInfoList, regionInfoList, $message, form } = this
      const { warning } = $message
      let message = ''
      for (let i = 0; i < regionInfoList.length; i++) {
        const { first, price, _continue, continue_price } = regionInfoList[i]
        if (first <= 0) {
          message += '首件/重量/体积应大于0；'
          isValid = false
        }
        if (price < 0) {
          message += '运费应大于等于0；'
          isValid = false
        }
        if (_continue <= 0) {
          message += '续件/重量/体积应大于0；'
          isValid = false
        }
        if (continue_price < 0) {
          message += '续费应大于等于0；'
          isValid = false
        }
      }
      if (form.appoint === 1) {
        for (let i = 0; i < appointInfoList.length; i++) {
          const { a_num, a_price } = appointInfoList[i]
          if (a_num <= 0) {
            message += '包邮件数应大于0；'
            isValid = false
          }
          if (a_price < 0) {
            message += '包邮金额应大于等于0'
            isValid = false
          }
          if (!isValid) {
            break
          }
        }
      }
      message !== '' && warning(message)
      return isValid
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid && this.checkFormList()) {
          this.buttonLoading = true
          const params = { ...this.form }
          params.regionInfo = this.regionInfoList
          params.appointInfo = []
          if (this.form.appoint === 1) {
            params.appointInfo = this.appointInfoList
          }
          if (this.form.id != null) {
            updateTemplates(params).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            }).finally(() => {
              this.buttonLoading = false
            })
          } else {
            addTemplates(params).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            }).finally(() => {
              this.buttonLoading = false
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除？').then(() => {
        this.loading = true
        return delTemplates(ids)
      }).then(() => {
        this.loading = false
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      }).finally(() => {
        this.loading = false
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('templates/templates/export', {
        ...this.queryParams
      }, `templates_${new Date().getTime()}.xlsx`)
    },
    onCitiesSelected(list) {
      const name = []
      list.map(p => {
        Object.keys(p).map(key => {
          if (['name', 'cityId', 'children'].indexOf(key) < 0) {
            delete p[key]
          }
        })
        p.children.map(c => {
          Object.keys(c).map(key => {
            if (['cityId'].indexOf(key) < 0) {
              delete c[key]
            }
          })
        })
        name.push(p.name)
      })
      const strName = name.join('，')
      let data = {
        '_continue': '1',
        'continue_price': '0',
        'first': '1',
        'price': '0',
        'region': list,
        'regionName': strName
      }
      if (this.$_currentProp === 'appointInfoList') {
        data = {
          'a_num': '1',
          'a_price': '0',
          'place': list,
          'placeName': strName
        }
      }
      this[this.$_currentProp].push(data)
      console.log(data)
    },
    addList(dataProp) {
      this.$_currentProp = dataProp
      this.visible = true
    },
    delList(index, dataProp) {
      this[dataProp].splice(index, 1)
    }
  }
}
</script>
